<template>
  <view class="chart_box">
    <scroll-view scroll-y class="scroll_view">
      <view>
        <view class="swiper-content">
          <!-- 健康评分 -->
          <view class="score-box">
            <view class="score-title">
              睡眠评分
              <uni-icons
                type="info"
                class="info-icon"
                size="20"
                color="#666666"
              ></uni-icons>
            </view>
            <view class="score-value">{{ score }}</view>
            <view class="score-desc">
              <view class="score-desc-item">
                <view class="score-line line-left"></view>
                <view class="score-block"></view>
              </view>
              <view class="score-desc-text">超过了74%的用户</view>
              <view class="score-desc-item">
                <view class="score-block"></view>
                <view class="score-line line-right"></view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 健康建议 -->
      <view class="advice-box">
        <view class="advice-title">智慧健康建议</view>
        <view class="advice-content">
          提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容
        </view>
        <view class="ai-btn">
          <AiPointReport></AiPointReport>
        </view>
      </view>
      <view
        style="
          margin-top: 15px;
          margin-bottom: 15px;
          font-size: 16px;
          color: #666666;
        "
        ><text>活动数据</text
        ><text style="float: right">{{ chooseDate }}</text></view
      >
      <view class="chart_item">
        <view class="chart_container">
          <view class="head">
            <view class="title">睡眠满足度</view>
            <uni-icons type="info" class="info-icon" size="20"></uni-icons>
          </view>

          <view class="sleep-container">
            <view class="sleep-info-container">
              <view class="sleep-item">
                <view style="color: #6f87ff"
                  >实际睡眠时长 - {{ actualSleepHours }}h
                  {{ actualSleepMinutes }}min</view
                >
              </view>
              <view class="sleep-item">
                <view style="color: #666666"
                  >推荐睡眠时长 - {{ recommendedSleepHours }}h
                  {{ recommendedSleepMinutes }}min</view
                >
              </view>
            </view>
            <view class="sleep-line-container">
              <image
                src="/static/health/line.png"
                mode="widthFix"
                style="width: 100%; height: 100%"
              ></image>
            </view>
            <view class="progress-container">
              <canvas
                class="progress-circle"
                canvas-id="sleepProgress"
              ></canvas>
              <text class="progress-percentage">{{ sleepRatioPercent }}</text>
            </view>
          </view>

          <!-- <table>
            <tr>
              <td
                rowspan="2"
                colspan="2"
                class="sleep-time-cell"
                style="vertical-align: middle"
              >
                <text style="font-size: 14px; color: #6f87ff"
                  >实际睡眠时长 {{ actualSleepHours }}h
                  {{ actualSleepMinutes }}min</text
                >
              </td>
              <td rowspan="4" class="image-cell">
                <image
                  src="/static/health/line.svg"
                  mode="widthFix"
                  style="width: 100%"
                ></image>
              </td>
              <td rowspan="4" class="progress-cell">
                <view class="progress-container">
                  <canvas
                    class="progress-circle"
                    canvas-id="sleepProgress"
                  ></canvas>
                  <text class="progress-percentage">{{
                    sleepRatioPercent
                  }}</text>
                </view>
              </td>
            </tr>
            <tr></tr>
            <tr>
              <td
                rowspan="2"
                colspan="2"
                class="sleep-time-cell"
                style="vertical-align: middle"
              >
                <text style="font-size: 14px; color: #666666"
                  >推荐睡眠时长 {{ recommendedSleepHours }}h
                  {{ recommendedSleepMinutes }}min</text
                >
              </td>
            </tr>
            <tr></tr>
          </table> -->
        </view>
      </view>

      <view class="chart_item">
        <view class="chart_container">
          <view class="head">
            <view class="title">睡眠时长</view>
            <uni-icons type="info" class="info-icon" size="20"></uni-icons>
          </view>
          <view>
            <view style="padding-left: 5px">
              <view class="time-row">
                <view class="time-row-num">{{ actualSleepHours }}</view>
                <view class="time-row-label">小时</view>
                <view class="time-row-num">{{ actualSleepMinutes }}</view>
                <view class="time-row-label">分钟</view>
              </view>
            </view>
            <view style="padding-left: 5px">
              <view style="font-size: 14px; color: #999999"
                >推荐睡眠时长: {{ recommendedSleepHours }}小时{{
                  recommendedSleepMinutes
                }}分钟</view
              >
            </view>
            <!-- <sleepChart
              v-if="boundingClientRect"
              ref="sleepChartRef"
              :key="sleepKey"
              :showX="false"
              :showTime="false"
              :value="sleepData"
              :width="boundingClientRect.width"
              :height="150"
            >
            </sleepChart> -->
            <view class="chart">
              <l-echart ref="sleepRef"></l-echart>
            </view>

            <view class="class-container">
              <view class="class-row">
                <view class="class-block block1"></view>
                <view class="class-label">
                  <view class="class-text">清醒时间：1小时15分</view>
                  <view class="class-range">5%</view>
                </view>
                <view class="class-state">
                  <TagState></TagState>
                </view>
              </view>
              <view class="class-row">
                <view class="class-block block2"></view>
                <view class="class-label">
                  <view class="class-text">快速眼动：1小时15分</view>
                  <view class="class-range">20%</view>
                </view>
                <view class="class-state">
                  <TagState></TagState>
                </view>
              </view>
              <view class="class-row">
                <view class="class-block block3"></view>
                <view class="class-label">
                  <view class="class-text">浅睡眠：1小时15分</view>
                  <view class="class-range">50%</view>
                </view>
                <view class="class-state">
                  <TagState></TagState>
                </view>
              </view>
              <view class="class-row">
                <view class="class-block block4"></view>
                <view class="class-label">
                  <view class="class-text">深度睡眠：1小时15分</view>
                  <view class="class-range">25%</view>
                </view>
                <view class="class-state">
                  <TagState></TagState>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="half-card-parent">
        <view class="half-card">
          <view class="head">
            <view class="title"> 卧床时间 </view>
            <uni-icons
              type="info"
              class="info-icon"
              size="20"
              color="#666666"
            ></uni-icons>
          </view>
          <view>
            <view>
              <view class="time-row">
                <view class="time-row-num">{{ actualSleepHours }}</view>
                <view class="time-row-label">小时</view>
                <view class="time-row-num">{{ actualSleepMinutes }}</view>
                <view class="time-row-label">分钟</view>
              </view>
            </view>

            <view>
              <view style="font-size: 12px; color: #999"
                >睡眠效率
                {{ sleepEfficiency }}
                %</view
              >
            </view>
          </view>
        </view>
        <view class="half-card">
          <view class="head">
            <view class="title">睡眠债</view>
            <uni-icons
              type="info"
              class="info-icon"
              size="20"
              color="#666666"
            ></uni-icons>
          </view>
          <view>
            <view>
              <view class="time-row">
                <view class="time-row-num">1</view>
                <view class="time-row-label">小时</view>
                <view class="time-row-num">5</view>
                <view class="time-row-label">分钟</view>
              </view>
            </view>
            <view>
              <view style="font-size: 12px; color: #999"
                >本周累计3小时15分钟</view
              >
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import * as echarts from "echarts";
import { queryMySleepInfoByDay } from "@/api/ring/chart.js";
import dayjs from "dayjs";
import store from "@/store/index.js";
import AiPointReport from "@/pages/ring/components/AiPointReport.vue";
import SleepChildBox from "@/pages/ring/components/sleep/index.vue";
import SleepChart from "../components/sleep/index.vue";
import TagState from "@/components/tag-state/index.vue";
const colors = ["#d1e7ff", "#7ebdff", "#2486ed", "#0059b8"];
const state = ["清醒", "快速眼动", "浅睡眠", "深度睡眠"];

const option = {
  color: colors,
  grid: {
    //绘图网格
    left: "3%",
    right: "3%",
    top: "3%",
    bottom: "10%",
    containLabel: true,
  },
  xAxis: {
    type: "time",
    interval: 3600 * 1000,
    min: "2009/6/1 1:00",
    axisLabel: {
      formatter: function (value) {
        var date = new Date(value);
        return getzf(date.getHours()) + ":00";
        function getzf(num) {
          if (parseInt(num) < 10) {
            num = "0" + num;
          }
          return num;
        }
      },
    },
  },
  yAxis: {
    data: ["清醒", "快速眼动", "浅睡眠", "深度睡眠"],
    axisLabel: {
      show: false,
    },
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false,
    },
  },
  series: [
    { name: state[0], type: "bar", data: [] },
    { name: state[1], type: "bar", data: [] },
    { name: state[2], type: "bar", data: [] },
    {
      type: "custom",
      renderItem: function (params, api) {
        var categoryIndex = api.value(0);
        var start = api.coord([api.value(1), categoryIndex]);
        var end = api.coord([api.value(2), categoryIndex]);
        var height = api.size([0, 1])[1];

        return {
          type: "rect",
          shape: echarts.graphic.clipRectByRect(
            {
              x: start[0],
              y: start[1] - height / 2,
              width: end[0] - start[0],
              height: height,
            },
            {
              // 当前坐标系的包围盒。
              x: params.coordSys.x,
              y: params.coordSys.y,
              width: params.coordSys.width,
              height: params.coordSys.height,
            }
          ),
          style: api.style(),
        };
      },
      encode: {
        x: [1, 2],
        y: 0,
      },
      data: [
        {
          itemStyle: { normal: { color: colors[2] } },
          name: "深睡",
          value: [0, "2009/6/1 1:28", "2009/6/1 5:00"],
        },
        {
          itemStyle: { normal: { color: colors[2] } },
          name: "深睡",
          value: [0, "2009/6/1 1:28", "2009/6/1 5:00"],
        },
        {
          itemStyle: { normal: { color: colors[2] } },
          name: "深睡",
          value: [0, "2009/6/1 1:28", "2009/6/1 5:00"],
        },
        {
          itemStyle: { normal: { color: colors[0] } },
          name: "深睡",
          value: [0, "2009/6/1 6:13", "2009/6/1 8:22"],
        },
        {
          itemStyle: { normal: { color: colors[1] } },
          name: "浅睡",
          value: [1, "2009/6/1 5:00", "2009/6/1 6:13"],
        },
        {
          itemStyle: { normal: { color: colors[1] } },
          name: "浅睡",
          value: [1, "2009/6/1 8:22", "2009/6/1 9:10"],
        },
        {
          itemStyle: { normal: { color: colors[1] } },
          name: "浅睡",
          value: [1, "2009/6/1 12:47", "2009/6/1 14:52"],
        },
        {
          itemStyle: { normal: { color: colors[2] } },
          name: "清醒",
          value: [2, "2009/6/1 9:10", "2009/6/1 12:47"],
        },
        {
          itemStyle: { normal: { color: colors[2] } },
          name: "清醒",
          value: [2, "2009/6/1 14:52", "2009/6/1 17:00"],
        },
      ],
    },
  ],
};

export default {
  props: {
    selectDateInfo: Object,
  },
  components: {
    SleepChart,
    AiPointReport,
    SleepChildBox,
    TagState,
  },
  data() {
    return {
      score: "",
      chooseDate: "",
      sleepArray: [],
      actualSleepHours: "--",
      actualSleepMinutes: "--",
      recommendedSleepHours: "--",
      recommendedSleepMinutes: "--",
      sleepRatio: 0,
      sleepRatioPercent: "--%",
      sleepKey: 0,
      sleepData: [],
      timeData: [],
      rect: null,
      dailySleepData: {},
      sleep: {
        chartRef: null,
        chart: null,
      },
    };
  },

  computed: {
    isLogin() {
      return store.state.userToken;
    },
    sleepEfficiency() {
      const { totalMinute, wakeUpMinute } = this.dailySleepData;
      return totalMinute > 0
        ? (
            ((totalMinute - Math.min(wakeUpMinute, totalMinute)) /
              totalMinute) *
            100
          ).toFixed(0)
        : "0";
    },
  },

  methods: {
    getTitle() {
      return "sleep";
    },
    updateChartData(date) {
      console.log("queryMySleepInfoByDay == date ==>", date);

      queryMySleepInfoByDay({
        dateStr:
          dayjs(date).format("YYYY-MM-DD") || dayjs().format("YYYY-MM-DD"),
        offsetMinutes: new Date().getTimezoneOffset(),
      })
        .then(async (res) => {
          console.log("queryMySleepInfoByDay", res.data);

          let totalMinutes = res.data.totalMinute;
          // actualSleepHours: '--',
          // actualSleepMinutes: '--',
          // recommendedSleepHours: '--',
          // recommendedSleepMinutes: '--',
          // sleepRatio: 0,
          // sleepRatioPercent: '--%'
          this.actualSleepHours = (totalMinutes / 60).toFixed(0);
          this.actualSleepMinutes = totalMinutes % 60;
          this.recommendedSleepHours = 8;
          this.recommendedSleepMinutes = 8;
          this.sleepRatio = (totalMinutes / 488).toFixed(2);
          this.sleepRatioPercent = this.sleepRatio * 100 + "%";
          this.score = res.data.score;

          const sleepData = res.data;

          const userSleepDBVos = sleepData.userSleepDBVos;
          let _sleepData = [];
          let _timeData = [];
          if (userSleepDBVos) {
            userSleepDBVos.forEach((_, i) => {
              _sleepData.push({
                type: _.value,
                minutes: Math.round(
                  dayjs(_.endTime).diff(dayjs(_.startTime), "minute")
                ),
              });
            });
            if (userSleepDBVos.length) {
              _timeData[0] = dayjs(userSleepDBVos[0].startTime).format("HH:mm");
              _timeData[1] = dayjs(
                userSleepDBVos[userSleepDBVos.length - 1].endTime
              ).format("HH:mm");
            }
          }

          this.sleepData = _sleepData;
          this.timeData = _timeData;
          this.sleepKey++;
          this.dailySleepData = res.data;
          this.drawProgressCircle();
        })
        .catch((error) => {
          console.log("sleep Data error", error);
        });
    },
    showTips() {
      uni.showToast({
        title: "这里是体征数据的相关说明内容",
        icon: "none",
      });
    },
    drawProgressCircle() {
      const ctx = uni.createCanvasContext("sleepProgress", this);
      const width = 70; // 画布宽度
      const height = 70; // 画布高度
      const radius = 40; // 圆的半径
      const centerX = width / 2;
      const centerY = height / 2;

      // 绘制灰色背景圆
      ctx.beginPath();
      ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
      ctx.setStrokeStyle("#ccc");
      ctx.setLineWidth(10);
      ctx.stroke();

      // 绘制进度条
      ctx.beginPath();
      ctx.arc(
        centerX,
        centerY,
        radius,
        -Math.PI / 2,
        -Math.PI / 2 + 2 * Math.PI * this.sleepRatio
      );
      ctx.setStrokeStyle("#6F87FF");
      ctx.setLineWidth(10);
      ctx.stroke();

      ctx.draw();
    },
    boundingClientRect() {
      return this.rect;
    },
  },

  async mounted() {
    if (!this.sleep.chartRef) {
      this.sleep.chartRef = this.$refs.sleepRef;
    }
    if (this.sleep.chartRef) {
      this.sleep.chart = await this.sleep.chartRef.init(echarts);
      this.sleep.chart.setOption(option);
    }

    let currentDate = dayjs().format("YYYY-MM-DD");
    if (this.selectDateInfo.fulldate) {
      currentDate = this.selectDateInfo.fulldate;
    }
    this.chooseDate = dayjs(currentDate).format("MM月DD日");
    const param = {
      type: "day",
      startTime: currentDate,
    };
    this.updateChartData(currentDate);
    const query = uni.createSelectorQuery().in(this);
    query
      .select(".chart")
      .boundingClientRect((data) => {
        console.log("boundingClientRect", data);
        this.rect = {
          width: data.width,
          height: data.height,
        };
      })
      .exec();
  },
  watch: {
    selectDateInfo: {
      handler(nv) {
        this.chooseDate = dayjs(nv.fulldate).format("MM月DD日");
        this.updateChartData(nv.fulldate);
      },
      immediately: true,
      deep: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.chart_box {
  width: 100%;
  height: 100%;
  color: black;

  .scroll_view {
    width: 100%;
    // height: calc(100vh - var(--status-bar-height) - 56rpx);
    height: calc(100% - 0rpx);
  }
  .w-70rpx {
    width: 48rpx;
  }

  .w-40rpx {
    width: 40rpx;
  }

  .chart_container {
    padding: 20rpx 30rpx;

    .head {
      width: 100%;
      height: 70rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .title {
        font-size: 32rpx;
        font-weight: 500;
        text-align: left;
        margin-left: 12rpx;
        flex-grow: 1; // 让标题靠左
      }

      .right-arrow-icon {
        width: 32rpx;
        height: 32rpx;
      }

      .tips-icon {
        width: 32rpx;
        height: 32rpx;
        margin-left: -360rpx;
        cursor: pointer;
      }
    }

    .refresh-tip {
      font-size: 24rpx;
      color: #999999;
      margin-top: 8rpx;
      margin-bottom: 16rpx;
    }

    table {
      border-collapse: collapse;
      width: 100%;
    }

    td {
      padding: 5px;
    }

    .sleep-time-cell {
      width: 45%;
    }

    .image-cell {
      width: 30%;
    }

    .progress-cell {
      width: 25%;
    }

    .progress-circle {
      width: 100px;
      height: 100px;
    }
  }
}

/* 外层卡片 */
.vital-signs-card {
  background: #fff;
  border-radius: 12rpx;
  padding: 16rpx;
  margin: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

/* 头部区域 */
.vital-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 12rpx;
}

.vital-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #ff5722;
  margin-bottom: 4rpx;
}

.vital-time {
  font-size: 22rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.refresh-desc {
  font-size: 22rpx;
  color: #666;
}

.chart_item {
  width: 100%;
  background-color: rgba(255, 255, 255, 0.5);
  border-radius: 30rpx;
  margin-top: 30rpx;
  overflow: hidden;
  position: relative;

  box-shadow: 0px -1px 6px 0px rgba(255, 255, 255, 0.25) inset;
}

.score-box {
  margin-top: 38rpx;
  text-align: center;

  .score-title {
    font-size: 32rpx;
    color: #999;
    margin-bottom: 8rpx;
  }

  .score-value {
    font-size: 128rpx;
    font-weight: 500;
    color: rgba(0, 0, 0, 1);
    margin-bottom: 42rpx;
  }

  .score-desc {
    font-size: 28rpx;
    color: #666;
  }
}

.advice-box {
  .advice-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #5667f8;
    margin-bottom: 16rpx;
  }

  .advice-content {
    font-size: 24rpx;
    color: #666;
    line-height: 1.6;
    margin-bottom: 24rpx;
  }

  .ai-btn {
    display: flex;
    align-items: center;
    gap: 8rpx;
    font-size: 24rpx;
    color: #2d99ff;
  }
}

.half-card-parent {
  display: flex;
  justify-content: space-between;
  margin-bottom: 50px;
}
.half-card {
  width: 48%;
  margin-top: 40rpx;
  background-color: rgba($color: white, $alpha: 0.5);
  backdrop-filter: blur(20rpx);
  border-radius: 8px;
  height: 250rpx;

  padding: 40rpx;

  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .head {
    width: 100%;
    height: 70rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .title {
      font-size: 32rpx;
      font-weight: 600;
      text-align: left;
      //margin-left: 6cap;
      margin-right: 12rpx;
    }
  }
}

.info-icon {
  font-weight: 500;
  color: rgba(0, 0, 0, 0.2) !important;
}

.score-desc {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
  color: #666;
  display: flex;
  align-items: center;
  margin-bottom: 40px;
  .score-desc-item {
    display: flex;
    align-items: center;
    .score-block {
      width: 5px;
      height: 5px;
      background: rgba(153, 153, 153, 1);
      border-radius: 1px;
    }
    .score-line {
      width: 60px;
      height: 2px;
    }
    .line-left {
      background: linear-gradient(
        90deg,
        rgba(153, 153, 153, 0) 0%,
        rgba(153, 153, 153, 1) 100%
      );
    }
    .line-right {
      background: linear-gradient(
        90deg,
        rgba(153, 153, 153, 1) 0%,
        rgba(153, 153, 153, 0) 100%
      );
    }
  }
  .score-desc-text {
    margin: 0 10px;
  }
}

.title-text {
  display: flex;
  align-items: center;
}
.title-content {
  margin-right: 8px;
}
.card-time {
  font-size: 14px;
  font-weight: 500;
  color: rgba(153, 153, 153, 1);
}

.sleep-container {
  display: flex;
  align-items: center;
  .sleep-info-container {
    flex-shrink: 0;
    .sleep-item {
      font-size: 14px;
      margin-bottom: 10px;
    }
  }
  .sleep-line-container {
    width: 88px;
    height: 34px;
    margin: 0 10px;
  }

  .progress-container {
    position: relative;
    width: 70px;
    height: 70px;
    margin: 0 auto;
  }

  .progress-percentage {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 16px;
    color: #6f87ff;
  }
}

.time-row {
  display: flex;
  align-items: flex-end;
  .time-row-num {
    font-size: 30px;
    color: #000000;
  }
  .time-row-label {
    font-size: 14px;
    color: #999999;
    margin-bottom: 5px;
  }
}
.class-row {
  display: flex;
  align-items: center;
  margin-bottom: 17px;
  .class-block {
    height: 15px;
    border-radius: 3px;
  }
  .class-label {
    flex: 1;
    font-size: 12px;
    color: rgba(0, 0, 0, 1);
    margin: 0 4px;
    display: flex;
    align-items: center;
    .class-range {
      color: rgba(35, 89, 248, 1);
      margin-left: 5px;
    }
  }
  .block1 {
    width: 14px;
    background: #d1e7ff;
  }
  .block2 {
    width: 29px;
    background: #7ebdff;
  }
  .block3 {
    width: 68px;
    background: #2486ed;
  }
  .block4 {
    width: 38px;
    background: #0059b8;
  }
}

.chart {
  width: 100%;
  height: 400rpx;
  position: relative;
  margin: 20px 0 10px;
}
</style>
